"use strict";

const axios = require("axios");
const semver = require("semver");
const urlJoin = require("url-join");

function getNpmInfo(npmName, registry = getDefaultRegistry(true)) {
    if (!npmName) {
        return null;
    }
    const url = urlJoin(registry, npmName);
    return axios
        .get(url)
        .then((res) => {
            return res.status === 200 ? res.data : null;
        })
        .catch((err) => {
            return Promise.reject(err);
        });
}

// 拿到npm所有的版本
async function getNpmVersions(npmName, registry) {
    const data = await getNpmInfo(npmName, registry);
    const versions = Object.keys((data || {}).versions || {});
    return versions;
}
function getDefaultRegistry(isChina) {
    return isChina ? "https://registry.npm.taobao.org" : "https://registry.npmjs.org";
}

function getSemverVersions(baseVersion, versions) {
    return versions.filter((item) => semver.satisfies(item, `^${baseVersion}`)).sort((a, b) => semver.gt(a, b));
}

async function getNpmSemverVersion(baseVersion, npmName, registry) {
    const versions = await getNpmVersions(npmName, registry);
    const versionsSemver = getSemverVersions(baseVersion, versions);
    return versionsSemver[0];
}

async function getNpmLatestVersion(npmName, registry) {
    let versions = await getNpmVersions(npmName, registry);
    if (versions) {
        return versions.sort((a, b) => semver.gt(a, b))[0];
    }
    return null;
}
module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmSemverVersion,
    getDefaultRegistry,
    getNpmLatestVersion,
};
